package com.xinyue.exceltool.logic;

import com.xinyue.exceltool.config.ExcelToolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 读取excel的入口类
 *
 * @author wgs
 */
@Service
public class ReadExcelService {

    private Logger logger = LoggerFactory.getLogger(ReadExcelService.class);
    @Autowired
    private ExcelToolConfig excelToolConfig;
    @Autowired
    private TableMd5Manager tableMd5Manager;
    private List<String> fileExt = Arrays.asList("xls", "xlsx");

    public void printConfig() {
        logger.info("-----配置信息-----\n{}", excelToolConfig.toString());
    }

    public void checkExcelFilePath() {
        if (StringUtils.isEmpty(excelToolConfig.getExcelFilePath())) {
            logger.error("Excel文件所在目录路径不能为空");
        }
    }

    public void readExcel() {
        try {
            File excelDir = new File(excelToolConfig.getExcelFilePath());
            if (excelDir.exists()) {
                readExcel(excelDir);
                tableMd5Manager.createTableMd5();
                logger.info("----读取所有配置表完成---");
            } else {
                logger.error("Excel文件配置路径不存在：{}", excelToolConfig.getExcelFilePath());
            }
        } catch (Exception e) {
            logger.error("excel转换异常", e);
        }
    }

    private boolean isNeedFile(String name) {
        if (name.startsWith("~")) {
            return false;
        }
        for (String extr : fileExt) {
            if (name.endsWith(extr)) {
                return true;
            }
        }
        return false;
    }

    private void readExcel(File excelDir) {
        File[] excelFiles = excelDir.listFiles();
        logger.info("开始读取Excel目录：{}，文件数量：{}", excelDir.getAbsolutePath(), excelFiles.length);
        for (File excelFile : excelFiles) {
            if (excelFile.isDirectory()) {
                readExcel(excelFile);
            } else {
                if (!isNeedFile(excelFile.getName())) {
                    logger.info("不支持的文件：{}", excelFile.getAbsolutePath());
                    continue;
                }
                logger.info("开始读取excel文件:{}", excelFile.getAbsolutePath());
                ReadOneExcelManager readOneExcelManager = new ReadOneExcelManager(excelFile, excelToolConfig);
                readOneExcelManager.readExcelData();
            }
        }
    }

}
